package li.kaeppe.travel.tracker.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import li.kaeppe.travel.tracker.domain.BlogEntry;

public class HibernateBlogEntryDaoImpl implements BlogEntryDao {
	/* **************************************************** */
	/* CONSTANTS */
	/* **************************************************** */
	
	private static final Log log = LogFactory.getLog(HibernateBlogEntryDaoImpl.class);

	/* **************************************************** */
	/* MEMBER FIELDS */
	/* **************************************************** */
	
	private SessionFactory sessionFactory;
	
	/* **************************************************** */
	/* CONSTRUCTOR */
	/* **************************************************** */

	/* **************************************************** */
	/* PUBLIC METHODS */
	/* **************************************************** */

	@SuppressWarnings("unchecked")
	public List<BlogEntry> getBlogEntriesByTrip(String tripKey) {
		if(log.isDebugEnabled()) {
			log.debug("HibernateBlogEntryDaoImpl -> getBlogEntriesByTrip()");
		}
		
		return this.getSession().createQuery("from BlogEntry b where b.trip.key = :tripKey").
		       setString("tripKey", tripKey).
		       list();
	}

	public BlogEntry getBlogEntryById(long id) {
		if(log.isDebugEnabled()) {
			log.debug("HibernateBlogEntryDaoImpl -> getBlogEntryById()");
		}
		
		return (BlogEntry) this.getSession().createQuery("from BlogEntry b where b.id = :id").
		       setLong("id", id).
		       uniqueResult();
	}

	public BlogEntry storeBlogEntry(BlogEntry blogEntry) {
		if(log.isDebugEnabled()) {
			log.debug("HibernateBlogEntryDaoImpl -> storeBlogEntry()");
		}
		
		this.getSession().saveOrUpdate(blogEntry);
		return blogEntry;
	}
	
	@SuppressWarnings("unchecked")
	public List<BlogEntry> getAllBlogEntries() {
		if(log.isDebugEnabled()) {
			log.debug("HibernateBlogEntryDaoImpl -> getAllBlogEntries()");
		}
		
		return this.getSession().createQuery("from BlogEntry").
		       list();
	}
	
	/* **************************************************** */
	/* PROTECTED METHODS */
	/* **************************************************** */

	/* **************************************************** */
	/* PRIVATE METHODS */
	/* **************************************************** */

	private Session getSession() {
		return this.getSessionFactory().getCurrentSession();
	}
	
	/* **************************************************** */
	/* GETTERS AND SETTERS */
	/* **************************************************** */
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
